package io.renren.modules.shop.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.renren.modules.api.annotation.AuthIgnore;
import io.renren.modules.api.entity.TokenEntity;
import io.renren.modules.api.service.TokenService;
import io.renren.modules.shop.entity.user.User;
import io.renren.modules.shop.service.user.IUserService;
import io.renren.modules.shop.util.SessionUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class QqWebInterceptor implements HandlerInterceptor{

	@Autowired
	private TokenService tokenService;

	@Autowired
	private IUserService iUserService;

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		
	}

	/**
	 *  true表示继续流程（如调用下一个拦截器或处理器）；
     *  false表示流程中断（如登录检查失败），不会继续调用其他的拦截器或处理器，此时我们需要通过response来产生响应；
	 */
/*	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
			User user = SessionUtil.getUser(request);
			if(user!=null){
				//session 中有用户信息
				
				return true;
			}
			response.getWriter().write("{\"res\":301}");

			return false;
	}*/

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
		AuthIgnore annotation;
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
		} else {
			return true;
		}

		//如果有@IgnoreAuth注解，则不验证token
		if(annotation != null){
			return true;
		}

		//从header中获取token
		String token = request.getHeader("token");
		//如果header中不存在token，则从参数中获取token
		if(StringUtils.isBlank(token)){
			token = request.getParameter("token");
		}

		//token为空
		if(StringUtils.isBlank(token)){
			response.getWriter().write("{\"res\":301}");
		} else {
			//根据token判断是司机还是用户,暂时用户端有商城
			if ("YH".equals(token.substring(0,2))) {    //如果是用户
				//查询用户token信息
				TokenEntity tokenEntity = tokenService.queryByToken(token);
//				 || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()
				if(tokenEntity == null){
					response.getWriter().write("{\"res\":301}");
					return false;
				}
				User user = iUserService.selectByPrimaryKey(new Long(tokenEntity.getUserId()).intValue());
				SessionUtil.setUser(request,user);

			}
			return true;
		}

		return false;
	}




}
